package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.enums.SServiceOrderStatusEnum;
import cn.huiyunche.base.service.enums.SServiceOrderTrailTypeEnum;
import cn.huiyunche.base.service.enums.WaybillContactsTypeEnum;
import cn.huiyunche.base.service.interfaces.*;
import cn.huiyunche.base.service.mappers.SOrderMapper;
import cn.huiyunche.base.service.mappers.SServiceOrderMapper;
import cn.huiyunche.base.service.mappers.SServiceOrderTrailMapper;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.base.service.model.SServiceOrderTrailExample.Criteria;
import cn.huiyunche.base.service.vo.CWaybillByIdVo;
import cn.huiyunche.base.service.vo.ServiceOrderTrailShowVo;
import cn.huiyunche.base.service.vo.ServiceOrderTrailVo;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SServiceOrderTrailServiceImpl implements SServiceOrderTrailService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SServiceOrderTrailServiceImpl.class);

    @Autowired
    private SServiceOrderTrailMapper sServiceOrderTrailMapper = null;

    @Autowired
    private SServiceOrderMapper sServiceOrderMapper = null;

    @Autowired
    private CWaybillService cWaybillService = null;

    @Autowired
    private SOrderMapper sOrderMapper = null;

    @Autowired
    private CWaybillDetailService cWaybillDetailService = null;

    @Autowired
    private UserService userService = null;

    @Autowired
    private CWaybillContactsService cWaybillContactsService = null;

    private CWaybillContactsService getCWaybillContactsService() {
        return this.cWaybillContactsService;
    }

    private UserService getUserService() {
        return this.userService;
    }

    private CWaybillDetailService getCWaybillDetailService() {
        return this.cWaybillDetailService;
    }

    private SOrderMapper getSOrderMapper() {
        return this.sOrderMapper;
    }

    private CWaybillService getCWaybillService() {
        return this.cWaybillService;
    }

    private SServiceOrderMapper getSServiceOrderMapper() {
        return this.sServiceOrderMapper;
    }

    private SServiceOrderTrailMapper getSServiceOrderTrailMapper() {
        return this.sServiceOrderTrailMapper;
    }

    @Override
    public Long add(SServiceOrderTrail trail) throws Exception {
        if (trail.getServiceOrderId() == null) {
            LOGGER.info("serviceOrderId is not null");
            throw new BusinessException("服务订单ID不能为空");
        } else if (trail.getInfo() == null) {
            LOGGER.info("info is not null");
            throw new BusinessException("物流信息不能为空");
        } else if (trail.getType() == null) {
            LOGGER.info("type is not null");
            throw new BusinessException("物流信息类型不能为空");
        }
        try {
            this.getSServiceOrderTrailMapper().insertSelective(trail);
        } catch (Exception e) {
            LOGGER.error("insert ServiceOrderTrail error : {}", e);
            throw new BusinessException("添加服务订单物流信息异常");
        }
        return trail.getId();
    }

    @Override
    public ServiceOrderTrailVo selectTrailByServiceOrderId(Long serviceOrderId) throws Exception {
        if (serviceOrderId == null) {
            LOGGER.info("serviceOrderId is not null");
            throw new BusinessException("服务订单ID不能为空");
        }
        ServiceOrderTrailVo vo = new ServiceOrderTrailVo();
        SServiceOrderTrailExample example = new SServiceOrderTrailExample();
        example.setOrderByClause(" create_time desc");
        example.createCriteria().andServiceOrderIdEqualTo(serviceOrderId)
                .andTypeEqualTo(SServiceOrderTrailTypeEnum.SERVICE_ORDER_STATUS.getValue());
        List<SServiceOrderTrail> trails = new ArrayList<SServiceOrderTrail>();
        try {
            trails = this.getSServiceOrderTrailMapper().selectByExample(example);
        } catch (Exception e) {
            LOGGER.error("selectTrailByServiceOrderId is error : {}", e);
            throw new BusinessException("查询当前服务订单物流信息异常");
        }
        List<ServiceOrderTrailShowVo> vos = new ArrayList<ServiceOrderTrailShowVo>();
        if (CollectionUtils.isNotEmpty(trails)) {
            for (SServiceOrderTrail trail : trails) {
                ServiceOrderTrailShowVo showVo = new ServiceOrderTrailShowVo();
                showVo.setStatus(trail.getStatus());
                showVo.setCreateTime(trail.getCreateTime());
                if (trail.getStatus() == SServiceOrderStatusEnum.WAIT_EXTRACT.getValue()) {
                    showVo.setInfo("已上报提车安排，等待提车。");
                    vos.add(showVo);
                } else if (trail.getStatus() == SServiceOrderStatusEnum.HAVE_EXTRACTED.getValue()) {
                    showVo.setInfo("您的车辆已提车，等待发车。");
                    vos.add(showVo);
                } else if (trail.getStatus() == SServiceOrderStatusEnum.HAVE_ISSUSD.getValue()) {
                    SServiceOrderTrailExample exmp = new SServiceOrderTrailExample();
                    exmp.setOrderByClause("create_time desc");
                    exmp.createCriteria().andServiceOrderIdEqualTo(serviceOrderId).andTypeEqualTo(SServiceOrderTrailTypeEnum.SERVICE_ORDER_ADDR.getValue());
                    List<SServiceOrderTrail> sTrails = this.getSServiceOrderTrailMapper().selectByExample(exmp);
                    if (CollectionUtils.isNotEmpty(sTrails)) {
                        for (SServiceOrderTrail sServiceOrderTrail : sTrails) {
                            if (StringUtils.isNotBlank(sServiceOrderTrail.getInfo())) {
                                ServiceOrderTrailShowVo trailShowVo = new ServiceOrderTrailShowVo();
                                trailShowVo.setStatus(sServiceOrderTrail.getStatus());
                                trailShowVo.setCreateTime(sServiceOrderTrail.getCreateTime());
                                trailShowVo.setInfo("当前车辆位置" + sServiceOrderTrail.getInfo());
                                vos.add(trailShowVo);
                            }
                        }
                    }
                    showVo.setInfo("您的车辆已发车。");
                    vos.add(showVo);
                } else if (trail.getStatus() == SServiceOrderStatusEnum.HAVE_DELIVERY.getValue()) {
                    showVo.setInfo("您的车辆已交车，等待确认收车。");
                    vos.add(showVo);
                } else if (trail.getStatus() == SServiceOrderStatusEnum.DONE.getValue()) {
                    showVo.setInfo("您的车辆已成功送达目的地。");
                    vos.add(showVo);
                } else if (trail.getStatus() == SServiceOrderStatusEnum.CANCELED.getValue()) {
                    showVo.setInfo("您的订单" + SServiceOrderStatusEnum.CANCELED.getText());
                    vos.add(showVo);
                }
            }
            // 查询服务订单
            SServiceOrder so = this.getSServiceOrderMapper().selectByPrimaryKey(serviceOrderId);
            // 查询订单号
            SOrder order = this.getSOrderMapper().selectByPrimaryKey(so.getCustomerOrderId());
            vo.setOrderCode(order.getOrderCode());
            vo.setTrails(vos);
            // 查询运单明细
            CWaybillDetail wayVos = this.getCWaybillDetailService().getByIdAndDispatchTimes(serviceOrderId, 1);
            if (null != wayVos) {
                // 查询运单
                CWaybillByIdVo cWaybill = this.getCWaybillService().selectById(wayVos.getWaybillId());
                // 查询承运商
                SUser user = this.getUserService().selectByPrimaryKey(cWaybill.getBidderId());
                vo.setBidderType(cWaybill.getBidderType());
                vo.setCarrier(user.getRealName());
                // 查询司机信息
                List<CWaybillContacts> contacts = this.getCWaybillContactsService().selectContacts(cWaybill.getId(),
                        WaybillContactsTypeEnum.DRIVER.getValue());
                CWaybillContacts contact = new CWaybillContacts();
                if (CollectionUtils.isNotEmpty(contacts)) {
                    contact = contacts.get(0);
                }
                vo.setDriver(contact.getContact());
                vo.setPhone(contact.getPhone());
            }
        }
        LOGGER.info("The current service order logistics information size : {}", trails.size());

        return vo;
    }

    @Override
    public SServiceOrderTrail getNewest(long serviceOrderId, int type) {
        LOGGER.info("getNewest param : {}", serviceOrderId);
        if (0 == serviceOrderId) {
            LOGGER.error("getNewest serviceOrderId must not be 0");
            throw new IllegalArgumentException("服务订单id不能为0");
        }

        SServiceOrderTrailExample example = new SServiceOrderTrailExample();
        example.setOrderByClause(" create_time DESC");
        Criteria criteria = example.createCriteria().andServiceOrderIdEqualTo(serviceOrderId);
        if (0 != type) {
            criteria.andTypeEqualTo(type);
        }
        List<SServiceOrderTrail> list = sServiceOrderTrailMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public int delete(Long serviceOrderId) {
        LOGGER.info("delete param {}", serviceOrderId);
        if (null == serviceOrderId) {
            LOGGER.info("delete param must not benull");
            throw new IllegalArgumentException("服务订单id不能为空");
        }

        SServiceOrderTrailExample example = new SServiceOrderTrailExample();
        example.createCriteria().andServiceOrderIdEqualTo(serviceOrderId);
        int count = sServiceOrderTrailMapper.deleteByExample(example);

        return count;
    }

}
